package cn.com.bsfit.netty.utils;

import cn.com.bsfit.netty.config.base.BaseConfigurable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 类名 StringHelper
 * 描述 Spring Bean 工具类
 *
 * @author hedonglin
 * @version 1.0
 * @date 2019/8/30 10:24
 */
@Slf4j
@Component
public class SpringBeanUtil implements ApplicationContextAware, BaseConfigurable {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtil.applicationContext = applicationContext;
        log.info("---------------------------------------------------------------------");
        log.info("========ApplicationContext配置成功========");
        log.info("---------------------------------------------------------------------");
    }

    public static <T> T getBean(Class<T> clazz) {
        return (T) applicationContext.getBean(clazz);
    }

    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    /** 通过Clazz返回指定的Beans */
    public static <T> Map<String, T> getBeansByType(Class<T> clazz) {
        return applicationContext.getBeansOfType(clazz);
    }
}